<script setup>
import { ref, computed } from 'vue'
// 导入相关接口
import {
    Delete,
    Edit,
    Refresh
} from '@element-plus/icons-vue'
import {
    getSetmealPageApi,
    editSetmealApi,
    deleteSetmealApi,
    addSetmealApi,
    querySetmealByIdApi,
    getCategoryListApi,
    querySetmealListApi,
    commonDownloadApi,
    setmealStatusByStatusApi
} from '@/api/backend/combination.js'
import { queryDishListApi } from '@/api/backend/dishes.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 页面相关
const drawer = ref(false)
// 获取分页数据代码
const currentPage = ref(1)
const pageSize = ref(5)
const disabled = ref(false)
const total = ref(0)
const tableData = ref([])
const handleSizeChange = (val) => {
    // 调用获取分页数据方法
    getSetmealPage();
}
const handleCurrentChange = (val) => {
    // 调用获取分页数据方法
    getSetmealPage();
}
// 映射关系
const typeMapping = {
    1: '启售',
    0: '停售'
}
// 计算属性：转换显示
const transformedTableData = computed(() => {
    return tableData.value.map(item => {
        return {
            ...item,
            status: typeMapping[item.status],
            price: '￥' + item.price / 100
        }
    })
})
// 获取分类信息分页数据
const getSetmealPage = async () => {
    const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
    }
    //调用接口,获取分类数据
    let result = await getSetmealPageApi(params);
    if (result.code === 1) {
        tableData.value = result.data.records || []
        total.value = result.data.total
        return;
    } else {
        return;
    }
}
getSetmealPage();
// 获取图片
const getImage = (image) => {
    return `/api/common/download?name=${image}`
}
// 添加,编辑的抽屉的相关方法
const handleClose = (done) => {
    ElMessageBox.confirm('您确定要关闭它吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        })
        .then(() => {
            // 确定后执行
            done();
            qc();
        })
        .catch(() => {
            // catch error
        })
}
function cancelClick() {
    drawer.value = false
    qc();
}
function confirmClick() {
    ElMessageBox.confirm(
        `您是否确认选择=> ${combinationData.value.name} ?`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        })
        .then(() => {
            submitForm(combinationDataref)
                .then((result) => {
                    if (result) {
                        // 确定后执行
                        if (title.value === '添加套餐') {
                            addSetmeal();
                        } else if (title.value === '编辑套餐') {
                            editSetmeal();
                        } else {
                            ElMessage.error('参数错误');
                        };
                        qc();
                        drawer.value = false
                        return;
                    }
                    // 处理结果为 false 的情况
                });
        })
        .catch(() => {
            // catch error
        })
}
// 抽屉的标题
const title = ref('')
// 显示抽屉的方法
const XSDrawers = (t, id) => {
    drawer.value = true;
    title.value = t;
    getCategoryList();
    getDishList();
    if (t === '添加套餐') {

    } else if (t === '编辑套餐') {
        // 获取需要编辑的套餐数据 id
        querySetmealById(id);

    } else {
        ElMessage.error('参数错误');
    };
}
const classify = ref([])
const combinationData = ref({
    categoryId: "",
    id: null,
    code: "",
    description: "",
    setmealDishes: [],
    image: "",
    name: "",
    price: null,
    status: 1
})
function qc() {
    title.value = '';
    combinationData.value = {
        id: null,
        categoryId: "",
        code: "",
        description: "",
        setmealDishes: [],
        image: "",
        name: "",
        price: null,
        status: 1
    }
    transferData.value = [];
    transferValue.value = [];
}
const getCategoryList = async () => {
    let result = await getCategoryListApi({ type: 2 });
    if (result.code === 1) {
        classify.value = result.data || []
        return;
    } else {
        return;
    }
}
const dialogFormVisible = ref(false)
const transferData = ref([])
const transferValue = ref([])
const getDishList = async () => {
    const dishData = ref({
        status: 1
    })
    let result = await queryDishListApi(dishData.value);
    if (result.code === 1) {
        transferData.value = result.data || []
        return;
    } else {
        return;
    }
}
const transferChange = () => {
    const ss = [];
    console.log(transferValue.value);
    transferValue.value.forEach((item, index) => {
        transferData.value.forEach((i) => {
            if (i.id == item) {
                const SD = {
                    copies: 1,
                    dishId: i.id,
                    name: i.name,
                    price: i.price
                };
                ss.push(SD);
                return;
            }
        })
    })
    combinationData.value.setmealDishes = ss;
}
const szcp = () => {
    dialogFormVisible.value = true;
    const ss = [];
    if (title.value == '编辑套餐') {
        combinationData.value.setmealDishes.forEach((item) => {
            let id = null;
            id = item.dishId;
            ss.push(id);
        })
        transferValue.value = ss;
        console.log(transferValue.value);
    } else {
        return;
    }
}
const onSuccess = (response, uploadFile) => {
    if (response.code === 1) {
        combinationData.value.image = response.data;
    }
}
const beforeUpload = (uploadFile) => {
    if (uploadFile) {
        const suffix = uploadFile.name.split('.')[1];
        const size = uploadFile.size / 1024 / 1024 < 2;
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
            ElMessage.error('上传图片只支持 png、jpeg、jpg 格式！');
            return false;
        }
        if (!size) {
            ElMessage.error('上传文件大小不能超过 2MB!');
            return false;
        }
        return true;
    }
}
const addSetmeal = async () => {
    let result = await addSetmealApi(combinationData.value);
    if (result.code === 1) {
        ElMessage.success(result.data ? result.data : '添加成功')
        getSetmealPage();
        return;
    } else {
        return;
    }
}
const querySetmealById = async (id) => {
    let result = await querySetmealByIdApi(id);
    if (result.code === 1) {
        combinationData.value.id = result.data.id;
        combinationData.value.categoryId = result.data.categoryId;
        combinationData.value.code = result.data.code;
        combinationData.value.description = result.data.description;
        combinationData.value.image = result.data.image;
        combinationData.value.name = result.data.name;
        combinationData.value.price = result.data.price;
        combinationData.value.status = result.data.status;
        combinationData.value.setmealDishes = result.data.setmealDishes
        return;
    } else {
        return;
    }
}
const editSetmeal = async () => {
    let result = await editSetmealApi(combinationData.value);
    if (result.code === 1) {
        ElMessage.success(result.data)
        getSetmealPage();
        return;
    } else {
        return;
    }
}
const ids = ref([]);
const handleSelectionChange = (val) => {
    let it = [];
    val.forEach((item) => {
        it.push(item.id);
    });
    ids.value = it;
}
const setmealStatusByStatus = async (s, i) => {
    const params = {
        id: '',
        status: s
    }
    if (i == null) {
        params.id = ids.value.join(',');
    } else {
        params.id = i;
    }
    let result = await setmealStatusByStatusApi(params);
    if (result.code === 1) {
        ElMessage.success(result.data)
        getSetmealPage();
        return;
    } else {
        ElMessage.error(result.msg ? result.msg : '修改失败')
        return;
    }
}
const deleteSetmeal = async (i) => {
    if (i == null) {
        i = ids.value.join(',');
    }
    let result = await deleteSetmealApi(i);
    if (result.code === 1) {
        ElMessage.success(result.data)
        getSetmealPage();
        return;
    } else {
        ElMessage.error(result.msg ? result.msg : '删除失败')
        return;
    }
}
const combinationDataref = ref(null)
var pricer = /^[1-9]\d*$/;
const combinationDataRules = {
    categoryId: [
        { required: true, message: '请选择分类', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入套餐描述', trigger: 'blur' },
    ],
    setmealDishes: [
        { required: true, message: '菜品数量不能为空', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入套餐名称', trigger: 'blur' },
    ],
    price: [
        { required: true, message: '请输入价格', trigger: 'blur' },
        { pattern: pricer, message: '价格单位为分,请输入整数', trigger: 'blur' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'blur' },
    ],
}
const submitForm = (fromEL) => {
    return new Promise((resolve, reject) => {
        fromEL.value.validate((valid) => {
            if (valid) {
                resolve(true);
            } else {
                resolve(false);
            }
        })
    });
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>套餐管理</span>
                <!-- button -->
                <el-button type="warning" plain @click="setmealStatusByStatus(1)">
                    批量启售
                </el-button>
                <el-button type="warning" plain @click="setmealStatusByStatus(0)">
                    批量停售
                </el-button>
                <el-button type="danger" plain @click="deleteSetmeal()">
                    批量删除
                </el-button>
                <el-button type="success" plain @click="XSDrawers('添加套餐', 1)">
                    添加套餐
                </el-button>
                <el-drawer v-model="drawer" :direction="RTL" :with-header="false" size="67%" :before-close="handleClose">
                    <template #default>
                        <div>
                            <h3>{{ title }}</h3>
                            <!-- 表单:菜品名,价格,菜品描述 -->
                            <el-form ref="combinationDataref" :model="combinationData" :rules="combinationDataRules">
                                <el-row :gutter="20">
                                    <el-col span="12">
                                        <el-form-item label="套餐名称:" prop="name">
                                            <el-input v-model="combinationData.name" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col span="12">
                                        <el-form-item label="套餐分类:" prop="categoryId">
                                            <el-select v-model="combinationData.categoryId" placeholder="选择分类"
                                                no-data-text="暂无数据">
                                                <el-option v-for="item in classify" :label="item.name" :value="item.id"
                                                    :key="item.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col span="12">
                                        <el-form-item label="套餐价格:" prop="price">
                                            <el-input v-model="combinationData.price" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col span="6">
                                        <el-form-item label="套餐图片:">
                                            <el-upload action="/api/common/upload" :show-file-list="false"
                                                :on-success="onSuccess" :before-upload="beforeUpload" ref="upload">
                                                <el-image style="width: auto; height: 40px; border:none;cursor: pointer;"
                                                    :src="getImage(combinationData.image)" preview-teleported="true">
                                                    <template #error>
                                                        <img src="@\assets\noImg.png"
                                                            style="width: auto; height: 40px; border:none;">
                                                    </template>
                                                </el-image>
                                            </el-upload>
                                        </el-form-item>
                                    </el-col>
                                    <el-col span="6">
                                        <el-form-item label="套餐菜品:" prop="setmealDishes">
                                            <el-button type="success" @click="szcp()">设置菜品</el-button>
                                            <!-- 套餐菜品,穿梭框 -->
                                            <el-dialog v-model="dialogFormVisible" title="套餐菜品" width="75%" align-center>
                                                <el-transfer v-model="transferValue" :data="transferData"
                                                    :titles="['候选菜品', '选中菜品']" :props="{
                                                        key: 'id',
                                                        label: 'name',
                                                    }" @change="transferChange"
                                                    style="display: flex;justify-content: center;align-items: center;" />
                                            </el-dialog>
                                        </el-form-item>
                                    </el-col>
                                    <el-table :data="combinationData.setmealDishes" style="width: 100%"
                                        :cell-style="{ textAlign: 'center' }"
                                        :header-cell-style="{ 'text-align': 'center' }">
                                        <el-table-column prop="name" label="菜品名字" />
                                        <el-table-column prop="price" label="菜品价格" />
                                        <el-table-column prop="copies" label="菜品数量">
                                            <template #default="{ row }">
                                                <el-input-number v-model="row.copies" :min="1" :max="100" />
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <el-col>
                                        <br>
                                        <el-form-item label="套餐描述:" prop="description">
                                            <el-input v-model="combinationData.description" type="textarea" />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </template>
                    <template #footer>
                        <div style="flex: auto">
                            <el-button @click="cancelClick">取消</el-button>
                            <el-button type="primary" @click="confirmClick">确认</el-button>
                        </div>
                    </template>
                </el-drawer>
            </div>
        </template>
        <el-table :data="transformedTableData" stripe style="width: 100%" :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
            <el-table-column label="选择" width="30px" type="selection"> </el-table-column>
            <el-table-column label="套餐名称" prop="name"></el-table-column>
            <el-table-column label="图片" prop="image" align="center">
                <template #default="{ row }">

                    <el-image style="width: auto; height: 40px; border:none;cursor: pointer;" :src="getImage(row.image)"
                        preview-teleported="true" :preview-src-list="[`/api/common/download?name=${row.image}`]">
                        <template #error>
                            <img src="@\assets\noImg.png" style="width: auto; height: 40px; border:none;">
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column label="套餐分类" prop="categoryName"></el-table-column>
            <el-table-column label="售价" prop="price"></el-table-column>
            <el-table-column label="售卖状态" prop="status">
                <template #default="{ row }">
                    <el-text type="primary">{{ row.status }}</el-text>
                    <el-button :icon="Refresh" size="small" circle
                        @click="setmealStatusByStatus((row.status == '停售' ? 1 : 0), row.id)" />
                </template>
            </el-table-column>
            <el-table-column label="最后操作时间" prop="updateTime"></el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <!-- 编辑按钮,弹出消息提示,选择切换状态或编辑全部 -->
                    <!-- 编辑方法,传一个菜品id 出去 -->
                    <el-button type="primary" :icon="Edit" circle @click="XSDrawers('编辑套餐', row.id)" />
                    <el-button type="danger" :icon="Delete" circle @click="deleteSetmeal(row.id)" />
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <div>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :disabled="disabled"
                :page-sizes="[5, 15, 30]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.el-pagination {
    margin-top: 10px;
    justify-content: center;
}

//
</style>